package binary_search;

/**
 * 朴素二分查找算法
 */
public class Demo20250325 {
    public int search(int[] nums, int target) {
        // 定义左右指针
        int left = 0;
        int right = nums.length - 1;
        // 进入循环的条件：left < right
        while (left <= right) {
            int mid = left + (right - left) / 2; // 防止溢出
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
}
